package cn.echoedu.control;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.echoedu.command.base.ExecuteParam;
import cn.echoedu.command.base.FailureParam;
import cn.echoedu.command.base.SuccessParam;
import cn.echoedu.constants.Role;
import cn.echoedu.entity.AClass;
import cn.echoedu.entity.ClassNotify;
import cn.echoedu.entity.ClassNotifyImage;
import cn.echoedu.entity.Image;
import cn.echoedu.entity.ReceiveClassNotify;
import cn.echoedu.entity.Student;
import cn.echoedu.entity.receivecommand.ClassNotifyFirstReceive;
import cn.echoedu.entity.receivecommand.ClassNotifyListDetailReceive;
import cn.echoedu.entity.receivecommand.ClassNotifyListReceive;
import cn.echoedu.entity.receivecommand.DeleteClassNotifyReceive;
import cn.echoedu.entity.receivecommand.MonitorAddNotifyReceive;
import cn.echoedu.entity.receivecommand.MonitorAddNotifyReceive.Pic;
import cn.echoedu.util.DateUtil;
import cn.echoedu.util.DigitUtil;
import cn.echoedu.util.ImageUtil;
import cn.echoedu.util.L;
import cn.echoedu.util.ObjectUtil;
import cn.echoedu.util.RandomUtil;

public class ClassNotifyControl extends BaseControl{
	private final String T = "ClassNotifyControl------->>";
	private final int ADD_NOTIFY_ERROR = -1;
    public void addClassNotify(HttpServletRequest request,
			HttpServletResponse response,
			MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M = "addClassNotify********>>";
		L.p(T+M);
		L.p(T+"���");
		L.p(T+"classcode"+monitoraddnotifyreceive.getAclasscode());
		if(monitoraddnotifyreceive.getAclasscode()==0){
			return;
		}
		int notifykey = addNotify(monitoraddnotifyreceive);
		if(ADD_NOTIFY_ERROR==notifykey){
			L.p(T+M);
			sendAddNotifyFailure(getFailureParam(request,response,monitoraddnotifyreceive.getCode()));
			return;
		}
		if(!"0".equals(monitoraddnotifyreceive.getIsdefault())&&!addReceiveList
				(monitoraddnotifyreceive,notifykey)){
			L.p(T+M+"add receive list error");
			sendAddNotifyFailure(getFailureParam(request,response,monitoraddnotifyreceive.getCode()));
			return;
		}
		L.p(T+M+"success");
		sendAddNotifySuccess(getSuccessParam(request,response,"",monitoraddnotifyreceive.getToken(),
				monitoraddnotifyreceive.getCode()));

	}
	private boolean addReceiveList(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int notifykey) {
		// TODO Auto-generated method stub
		final String M = "addReceiveList********>>";
		L.p(T+M);
		if(isDefault(monitoraddnotifyreceive)){
			return addClassNotifyDefault(monitoraddnotifyreceive,notifykey);
		}else{
			return whenIsNotDefault(monitoraddnotifyreceive,notifykey)==null?false:true;
		}
	}
	private boolean isDefault(MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "isDefault***********>>";
		L.p(T+M);
		return 0==(monitoraddnotifyreceive.getIsdefault())?true:false;
	}
	private boolean addClassNotifyDefault(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int notifykey) {
		// TODO Auto-generated method stub
		final String M = "addSchoolNotifyDefault***********>>";
		L.p(T+M);
		return  getReceiveClassNotifyModel().putInfoWhenDefault(
				monitoraddnotifyreceive,notifykey);

	}
	private List<Integer> whenIsNotDefault(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int notifykey) {
		// TODO Auto-generated method stub
		final String M  = "whenIsNotDefault********>>";
		L.p(T+M);
		return addReceivePeople(monitoraddnotifyreceive,notifykey);
	}
	private List<Integer> addReceivePeople(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int notifykey) {
		// TODO Auto-generated method stub
		final String M  = "addReceivePeople*********>>";
		L.p(T+M);
		return getReceiveClassNotifyModel().putInfoWhenIsNotDefault(
				monitoraddnotifyreceive,notifykey);
	}
	private int addNotify(MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "addNotify*******>>";
		L.p(T+M);
		L.p(T+"通知");
		int classnotifykey = ADD_NOTIFY_ERROR;
		classnotifykey = addNotifyContent(monitoraddnotifyreceive);
		if(classnotifykey==ADD_NOTIFY_ERROR){
			deleteNotifyContent(classnotifykey);
			return ADD_NOTIFY_ERROR;
		}
		List<String> imageurllist = generateImage(monitoraddnotifyreceive);
		if(imageurllist==null||imageurllist.isEmpty()){
			return classnotifykey;
		}
		List<Integer> imagelist = addNotifyImage(monitoraddnotifyreceive,imageurllist);
		L.p(T+M+"imagelist:"+imagelist);
		if(imagelist==null||imagelist.size()<=0){
			deleteNotify(classnotifykey);
			return ADD_NOTIFY_ERROR;
		}
		if(!addClassNotifyImage(classnotifykey,imagelist)){
			deleteNotify(classnotifykey);
			deleteNotifyImage(imagelist,imageurllist);
			return ADD_NOTIFY_ERROR;
		}
		return classnotifykey;
	}
	private void deleteNotifyImage(List<Integer> imagelist,
			List<String> imageurllist) {
		// TODO Auto-generated method stub

	}
	private boolean addClassNotifyImage(int classnotifykey,
			List<Integer> imagelist) {
		// TODO Auto-generated method stub
		final String M  = "addClassNotifyImage******>>";
		L.p(T+M);
		List<ClassNotifyImage> classnotifyimagelist = new ArrayList<ClassNotifyImage>();
		for(Integer imageid:imagelist){
			ClassNotifyImage classnotifyimage = new ClassNotifyImage();
			ClassNotify classnotify = new ClassNotify();
			classnotify.setClassnotify(classnotifykey);
			classnotifyimage.setClassnotify(classnotify);
			Image image = new Image();
			image.setImageid(imageid);
			if(imageid==-1){
				return false;
			}
			classnotifyimage.setImageid(image);
			classnotifyimagelist.add(classnotifyimage);
		}
		if(null==getClassNotifyImageModel().putListInfo(classnotifyimagelist)){
			return false;
		}
		return true;
	}
	private void deleteNotify(int schoolnotifykey) {
		// TODO Auto-generated method stub

	}
	private List<Integer> addNotifyImage(
			MonitorAddNotifyReceive monitoraddnotifyreceive,
			List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "addNotifyImage********>>";
		L.p(T+M);
		return insertIntoImageTable(imageurllist);
	}
	private List<Integer> insertIntoImageTable(List<String> imageurllist) {
		// TODO Auto-generated method stub
		final String M  = "insertIntoImageTable******>>";
		L.p(T+M);

		try{
			List<Image> imagelist = new ArrayList<Image>();
			for(String imageurl:imageurllist){
				L.p("add to list imageurl");
				Image image = new Image();
				image.setImagename(imageurl);
				image.setImagesrc(imageurl);
				//				int imagekey = getImageModel().putInfoGetPrimaryKey(image);
				//				if(imagekey==-1){
				//					deleteNotifyImage(imageidlist,imageurllist);
				//					return null;
				//				}
				//				imageidlist.add(imagekey);
				imagelist.add(image);
			}
			return getImageModel().putListInfo(imagelist);
		}catch(Exception e){
			e.printStackTrace();

		}
		return null;
	}
	private void deleteNotifyContent(int schoolnotifykey) {
		// TODO Auto-generated method stub

	}
	private int addNotifyContent(MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "addNotifyContent*******>>";
		L.p(T+M);
		int currentnotifymaxid = getMaxIdOfNotifyOfAClass(monitoraddnotifyreceive);
		int resultid = getCurrentMaxId(monitoraddnotifyreceive,currentnotifymaxid);

		L.p(T+M+currentnotifymaxid);
		if(currentnotifymaxid==0||currentnotifymaxid%10!=0){
			if(insertClassNotify(monitoraddnotifyreceive,resultid)){
				return resultid;
			}
		}else{
			int currentminiid = getClassNotifyModel().getCurrentMiniIdOfNotify(monitoraddnotifyreceive);
			if(updateClassNotify(monitoraddnotifyreceive,currentminiid)){
				deleteImage(currentminiid);
				deleteReceiveList(currentminiid);
				return currentminiid;
			}
		}
		return -1;
	}
	private void deleteReceiveList(int currentnotifyid) {
		// TODO Auto-generated method stub
        getReceiveClassNotifyModel().deleteByClassNotifyid(currentnotifyid);
	}
	private void deleteImage(int currentnotifyid) {
		// TODO Auto-generated method stub
		List<ClassNotifyImage> classnotifyimagelist = getImageSrcs(currentnotifyid);
        deleteImageFiles(classnotifyimagelist);
		deleteNotifyImages(currentnotifyid);
		deleteImageDatas(classnotifyimagelist);
	}
	private List<ClassNotifyImage> getImageSrcs(int currentnotifyid) {
		// TODO Auto-generated method stub
		return getClassNotifyImageModel().getImageSrcsByNotifyid(currentnotifyid);
	}
	private void deleteImageFiles(List<ClassNotifyImage> classnotifyimagelist){
		// TODO Auto-generated method stub
		L.p("delete iamge Files");
		for(int i=0,len=classnotifyimagelist.size();i<len;i++){
			if(classnotifyimagelist.get(i)!=null&&
					classnotifyimagelist.get(i).getImageid()!=null
					&&classnotifyimagelist.get(i).getImageid().getImagesrc()!=null){
				L.p("delete iamge Files&&&&&&&"+i);
				ImageUtil.deleteFileByGroupAndName(
						classnotifyimagelist.get(i).getImageid().getImagesrc());
			}
		}
	}
	private void deleteNotifyImages(int currentnotifyid){
		// TODO Auto-generated method stub
		getClassNotifyImageModel().deleteByClassNotifyId(currentnotifyid);
	}
	private void deleteImageDatas(List<ClassNotifyImage> classnotifyimagelist){
		// TODO Auto-generated method stub
		List<String> sqllist = new ArrayList<String>();
		for(int i=0,len=classnotifyimagelist.size();i<len;i++){
			if(classnotifyimagelist!=null&&classnotifyimagelist.get(i)!=null
					&&classnotifyimagelist.get(i).getImageid()!=null
					&&classnotifyimagelist.get(i).getImageid().getImageid()!=0)
			{ 
				String sql = "delete from image where imageid="
						+classnotifyimagelist.get(i).getImageid().getImageid();
				sqllist.add(sql);
			}
		}
		getImageModel().deleteBySqls(sqllist);
	}
	private boolean updateClassNotify(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int currentminiid) {
		// TODO Auto-generated method stub
		ClassNotify classnotify = initClassNotify(monitoraddnotifyreceive,currentminiid);
		return getClassNotifyModel().updateClassNotify(classnotify,classnotify);
	}
	private boolean insertClassNotify(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int resultid) {
		// TODO Auto-generated method stub
		try{
			return getClassNotifyModel().addClassNotifyKeyContent(
					initClassNotify(monitoraddnotifyreceive,resultid));
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;

	}
	private ClassNotify initClassNotify(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int currentminiid){
		ClassNotify   classnotify = new ClassNotify();
        classnotify.setClassnotify(currentminiid);
		classnotify.setTitle(monitoraddnotifyreceive.getTheme());
		classnotify.setPlace(monitoraddnotifyreceive.getPlace());
		classnotify.setStarttime(DateUtil.stringToDate(
				monitoraddnotifyreceive.getStarttime(),"yyyy-mm-dd"));
		classnotify.setEndtime(DateUtil.stringToDate(
				monitoraddnotifyreceive.getEndtime(),"yyyy-mm-dd"));
		classnotify.setRemindertime(DateUtil.stringToDate(
				monitoraddnotifyreceive.getAttion_time(),"yyyy-mm-dd"));
		classnotify.setContent(monitoraddnotifyreceive.getContent());
		Student student = new Student();
		student.setStudentnumber(monitoraddnotifyreceive.getUser_number());
		classnotify.setStudent(student);
		AClass aclass = new AClass();
		aclass.setClasscode(monitoraddnotifyreceive.getAclasscode());
		classnotify.setAclass(aclass);
		java.util.Date curDate = new java.util.Date();
		Timestamp d = new Timestamp(curDate.getTime());
        classnotify.setPublishtime(d);
		L.p("publishtime"+classnotify.getPublishtime());
		classnotify.setHitcount(0);
		return classnotify;
	}
	private int getCurrentMaxId(
			MonitorAddNotifyReceive monitoraddnotifyreceive, int maxid) {
		// TODO Auto-generated method stub
		if(ObjectUtil.isO(maxid)){
			maxid = whenCurrentIdOfClassNotifyIsNull(monitoraddnotifyreceive);

		}else if(maxid%10!=0){
			maxid = whenCurrentIdOfClassNotifyIsNotNull(maxid);
		}
		return maxid;
	}
	private int whenCurrentIdOfClassNotifyIsNotNull(int maxid) {
		// TODO Auto-generated method stub
		return DigitUtil.updateMaxIdWhenNotNull(maxid);
	}
	private int whenCurrentIdOfClassNotifyIsNull(
			MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		int currentmaxid = getMaxIdOfNotify(monitoraddnotifyreceive);

		return DigitUtil.updateMaxIdWhenNull(currentmaxid);
	}
	private int getMaxIdOfNotify(MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		return getClassNotifyModel().getMaxIdOfNotify(monitoraddnotifyreceive);
	}
	private int getMaxIdOfNotifyOfAClass(
			MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub

		return getClassNotifyModel().getMaxIdOfNotifyOfAClass(monitoraddnotifyreceive);
	}
	private List<String> generateImage(
			MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		final String M  = "generateImgae******>>";
		L.p(T+M);
		if(monitoraddnotifyreceive.getPic_url_list()==null||
				monitoraddnotifyreceive.getPic_url_list().size()==0){
			return null;
		}
		List<String> imageurllist = new ArrayList<String>();
		L.p(T+M+"111**"+monitoraddnotifyreceive);
		L.p(T+M+"222**"+monitoraddnotifyreceive.getPic_url_list());

		for(Pic base64:monitoraddnotifyreceive.getPic_url_list()){
			imageurllist.add(beginGenerateImage(base64.getPic_url(),
					RandomUtil.getUUIDnumber()));
		}
		return imageurllist;
	}
	private String beginGenerateImage(String pic_base64, String uuiDnumber) {
		// TODO Auto-generated method stub
		final String M  = "beginGenerateImage*****>>";
		L.p(T+M);
		return ImageUtil.base64strToImage(pic_base64, "classnotify",uuiDnumber+"");
	}

	public void queryClassNotifyByPage(HttpServletRequest request,
			HttpServletResponse response,
			ClassNotifyListReceive classnotifyreceive) {
		// TODO Auto-generated method stub
		switch (classnotifyreceive.getRole()){
		case Role.student:
			whenStudentQuery(request,response,classnotifyreceive);
			break;
		case Role.teacher:
			whenTeacherQuery(request,response,classnotifyreceive);
			break;
		default:

		}
	}
	private void whenTeacherQuery(HttpServletRequest request,
			HttpServletResponse response,
			ClassNotifyListReceive classnotifyreceive) {
		// TODO Auto-generated method stub
		List<ReceiveClassNotify> receiveschoolnotifylist = 
				(List<ReceiveClassNotify>)getReceiveClassNotifyModel()
				.whenTeacherQuery(classnotifyreceive);
		List<ClassNotify> schoolnotifylist = 
				getClassNotifyModel().queryByReceiveClassNotifys(
						receiveschoolnotifylist);
		sendListSuccess(getSuccessParam(request, response, schoolnotifylist,
				classnotifyreceive.getToken(),
				classnotifyreceive.getCode()));   
	}

	private void whenStudentQuery(HttpServletRequest request,
			HttpServletResponse response,
			ClassNotifyListReceive classnotifyreceive) {
		// TODO Auto-generated method stub
		List<ReceiveClassNotify> receiveclassnotifylist = 
				(List<ReceiveClassNotify>)getReceiveClassNotifyModel()
				.whenStudentQuery(classnotifyreceive);
		List<ClassNotify> schoolnotifylist = getClassNotifyModel()
				.queryByReceiveClassNotifys(receiveclassnotifylist);
		sendListSuccess(getSuccessParam(request, response, schoolnotifylist,
				classnotifyreceive.getToken(),
				classnotifyreceive.getCode()));  
	}
	public void queryClassNotifyDetail(HttpServletRequest request,
			HttpServletResponse response,
			ClassNotifyListDetailReceive classnotifydetailreceive) {
		// TODO Auto-generated method stub
		final String M = "queryClassNotifyDetail--------->>";
		L.p(T+M);
		List<ClassNotifyImage> classnotifyimagelist = getClassNotifyImageModel()
				.queryDetailByClassNotifyId(classnotifydetailreceive
						.getClassnotifyid());
		sendDetailSuccess(getSuccessParam(request, response, classnotifyimagelist,
				classnotifydetailreceive.getToken(),
				classnotifydetailreceive.getCode()));
	}
	public void deleteClassNotify(HttpServletRequest request,
			HttpServletResponse response,
			DeleteClassNotifyReceive deleteclassnotify) {
		// TODO Auto-generated method stub
		int classnotifyid = deleteclassnotify.getClassnotifyid();
		List<ClassNotifyImage> classnotifyimagelist = 
				queryClassNotifyImageById(classnotifyid);
		deleteClassNotifyImageById(classnotifyid);
		deleteReceiveClassNotifyByClassNotifyId(classnotifyid);
		List<String> imageurllist = 
				queryImageUrlByClassNotifyImageList(classnotifyimagelist);
		deleteClassImageByClassNotifyImageList(classnotifyimagelist);
		deleteClassNotifyById(classnotifyid);
		deleteImageFileByUrlList(imageurllist);
		sendDeleteSuccess(getSuccessParam(request, response, "",
				deleteclassnotify.getToken(),
				deleteclassnotify.getCode()));
	}
	private boolean deleteReceiveClassNotifyByClassNotifyId(int classnotifyid) {
		// TODO Auto-generated method stub
		return getReceiveClassNotifyModel().deleteByClassNotifyid(classnotifyid);
	}
	private List<ClassNotifyImage> queryClassNotifyImageById(int classnotifyid) {
		// TODO Auto-generated method stub
		return getClassNotifyImageModel().queryByClassNotifyId(classnotifyid);
	}
	private void deleteImageFileByUrlList(List<String> imageurllist) {
		// TODO Auto-generated method stub
		for(int i=0,len=imageurllist.size();i<len;i++){
			String imageurl = imageurllist.get(i);
			ImageUtil.deleteFileByGroupAndName(imageurl);
		}
	}
	private boolean deleteClassImageByClassNotifyImageList(
			List<ClassNotifyImage> classnotifyimagelist) {
		// TODO Auto-generated method stub
		return getImageModel().deleteByClassNotifyImageList(classnotifyimagelist);

	}
	private List<String> queryImageUrlByClassNotifyImageList(
			List<ClassNotifyImage> classnotifyimagelist) {
		// TODO Auto-generated method stub
		return getImageModel().queryAllByClassNotifyImage(classnotifyimagelist);

	}
	private boolean deleteClassNotifyImageById(int classnotifyid) {
		// TODO Auto-generated method stub
		return getClassNotifyImageModel().deleteByClassNotifyId(classnotifyid);
	}
	private boolean deleteClassNotifyById(int classnotifyid) {
		// TODO Auto-generated method stub
		return getClassNotifyModel().deleteNotifyById(classnotifyid);
	}



	private void sendDetailSuccess(SuccessParam successparam) {
		// TODO Auto-generated method stub
		getResponseService().doClassNotifyDetailSuccess(successparam);
	}
	private void sendDetailFailure(FailureParam failureparam) {
		// TODO Auto-generated method stub
		getResponseService().doClassNotifyDetailFailure(failureparam);
	}
	private void sendListSuccess(SuccessParam successparam){
		getResponseService().doQueryClassNotifyList(successparam);
	}
	private void sendListFailure(FailureParam failureparam){
		getResponseService().doQueryClassNotifyListFailure(failureparam);
	}
	private void sendDeleteSuccess(SuccessParam successparam){
		getResponseService().doDeleteClassNotifySuccess(successparam);
	}
	private void sendDeleteFailure(FailureParam failureparam){
		getResponseService().doDeleteClassNotifyFailure(failureparam);
	}
	private void sendAddNotifySuccess(SuccessParam sucessparam){
		getResponseService().doAddClassNotifySuccess(sucessparam);
	}
	private void sendAddNotifyFailure(FailureParam failureparam){
		getResponseService().doAddNotifyClassFailure(failureparam);

	}
	public void doClassNotifyFirst(HttpServletRequest request,
			HttpServletResponse response,
			ClassNotifyFirstReceive classnotifyfirst) {
		// TODO Auto-generated method stub
		ClassNotify classnotify = 
				getClassNotifyModel().queryClassNotifyFirst(classnotifyfirst);
		sendFirstSuccess(getSuccessParam(request, response, classnotify,
				classnotifyfirst.getToken(),classnotifyfirst.getCode()));
	}
	private void sendFirstSuccess(SuccessParam successParam) {
		// TODO Auto-generated method stub
		getResponseService().doClassNotifyFirst(successParam);
	}
	private void sendFirstFail(HttpServletRequest request,HttpServletResponse response){
		FailureParam failureParam = new FailureParam();
		getResponseService().doClassNotifyFirstFail(failureParam);
	}
	public void doNoAuthority(HttpServletRequest request,
			HttpServletResponse response,MonitorAddNotifyReceive monitoraddnotifyreceive) {
		// TODO Auto-generated method stub
		ExecuteParam executeparam = new ExecuteParam();
		executeparam.setRequest(request);
		executeparam.setResponse(response);
		executeparam.setCode(monitoraddnotifyreceive.getCode());
		executeparam.setToken(monitoraddnotifyreceive.getToken());
		getResponseService().doNoAuthority(executeparam);
	}

}
